import {Component, OnDestroy, OnInit} from '@angular/core';
import {Message} from "../../model/Message";
import {CustomService} from "../../services/custom.service";
import {AlertService} from "../../services/alert.service";
import {CallcenterService} from "../../services/callcenter.service";
import {WebSocketSubject} from "rxjs/internal/observable/dom/WebSocketSubject";
import {webSocket} from "rxjs/webSocket";
import {delay, filter, interval, retryWhen, take} from "rxjs";
import {OnlineUser} from "../../model/OnlineUser";

@Component({
  selector: 'app-callcenter',
  templateUrl: './callcenter.component.html',
  styleUrls: ['./callcenter.component.css']
})
export class CallcenterComponent implements OnInit ,OnDestroy{
  ml: Array<Message>;
  socket$: any;
  msgtext: string;
  WS_ENDPOINT = "ws://192.168.2.66:2066/callcenter";
  sendping$:any;
  myuserid:string;
  mynickname:string;

  ul:Array<OnlineUser>;
  onlineuserssocket$:any;
  ONLINEUSER_ENDPOINT="ws://192.168.2.66:2066/imdashboard";

  touserid:string
  selectcustomname:string
  inputtext:string;


  constructor(private customservice:CustomService,
              private alertservice:AlertService,
              private callservice: CallcenterService) {
    this.ml = new Array<Message>();
    this.ul=new Array<OnlineUser>();
    this.touserid='';
    this.selectcustomname='';

  }

  ngOnInit(): void {
  this.init()
    this.initOnlineUser()
  }

  ngOnDestroy(): void {
    if(this.socket$!=null&&!this.socket$.closed){
      this.socket$.complete();
      this.sendping$.complete();
    }
    if(this.onlineuserssocket$!=null&&!this.socket$.closed){
      this.onlineuserssocket$.complete();
    }

  }

  private async getNewWebSocket() :Promise<WebSocketSubject<any>>{
    //console.log('条件触发');
    return webSocket({url:this.WS_ENDPOINT,
      deserializer:({data})=>{
        let m=new Message();
        // console.log(data);
        m=JSON.parse(data)
        return m;
      }
      //closeObserver:(event:any)=>this.closeedConnect()
    });

  }


  init(){
    if (!this.socket$ || this.socket$.closed){
      this.getNewWebSocket()
        .then((data:any)=>{
          if(data){
            this.socket$=data;
            this.socket$
              .pipe(
                retryWhen(errors => errors.pipe(delay(1000), take(2))),
              )
              .subscribe((m:Message)=>{
               // console.dir(m);
                let type=m.type;
                switch (type){
                  case "REGISTFORADMIN":
                    this.myuserid=m.fromuserid;
                    this.mynickname=m.nickname;
                    this.customservice.token=m.token;
                    break;
                  case "ADMINPING":
                    //console.log('before   '+this.customservice.token);
                    this.customservice.token=m.token;
                   // console.log('after  '+this.customservice.token);
                    break;
                  case "MESSAGE":

                    console.dir(m);


                    break;

                }



                // this.ml.push(m);
              })

            this.sendping$=interval(2*60*1000)
              .subscribe(()=>{
                this.sendping()
              })

            this.sendRegist();

          }
        })
    }
  }

  sendping(){
    let msg = new Message();
    msg.type = 'ADMINPING';
    msg.fromuserid = this.customservice.userid;
    msg.token=this.customservice.token;
    this.socket$.next(msg)

  }

  sendRegist(){
    let msg=new Message();
    msg.type='REGISTFORADMIN';
    msg.fromuserid=this.customservice.userid;
    msg.token=this.customservice.token;
    this.socket$.next(msg);
  }


  private async getOnlineUserSocket() :Promise<WebSocketSubject<any>>{
    //console.log('条件触发');
    return webSocket({url:this.ONLINEUSER_ENDPOINT,
      deserializer:({data})=>{
        let ul=new Array<OnlineUser>();

        ul=JSON.parse(data)
        return ul;
      }
      //closeObserver:(event:any)=>this.closeedConnect()
    });

  }


  initOnlineUser(){
    if (!this.onlineuserssocket$ || this.onlineuserssocket$.closed){
      this.getOnlineUserSocket()
        .then((data:any)=>{
          if(data){
            this.onlineuserssocket$=data;
            this.onlineuserssocket$
              .pipe(
                // filter((ul:Array<OnlineUser>,index:number)=>{
                //  return  ul[index].role==='customer'
                // }),
                retryWhen(errors => errors.pipe(delay(1000), take(2))),
              )
              .subscribe((ul:Array<OnlineUser>)=>{
                //console.dir(ul);
                this.ul=new Array<OnlineUser>();
                this.ul=ul
                this.ul=this.ul.filter((u:OnlineUser)=>u.role==='customer')


                // this.ml.push(m);
              })
          }
        })
    }
  }

  onClickCustomer(userid:string,nickname:string){
    this.touserid=userid;
    this.selectcustomname=nickname;
  }


  sendTextMessage(){
    let msg=new Message();
    msg.type='MESSAGE';
    msg.fromuserid=this.myuserid;
    msg.content=this.inputtext;
    msg.token=this.customservice.token;
    msg.nickname=this.mynickname
    msg.touserid=this.touserid;

    this.socket$.next(msg);

  }

}
